package com.ithui.tidal.user.service.impl;

import cn.hutool.core.util.StrUtil;
import com.ithui.tidal.common.constant.RedisKey;
import com.ithui.tidal.common.utils.JwtUtils;
import com.ithui.tidal.common.utils.RedisUtils;
import com.ithui.tidal.user.service.LoginService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.Objects;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 *@Author: ithui
 *@CreateTime: 2025-07-31
 */
@Service
public class LoginServiceImpl implements LoginService {

    /**
     * token过期时间设置，单位天
     */
    private static final int TOKEN_EXPIRE_DAYS = 3;
    /**
     * token剩余时间，单位天
     */
    private static final int TOKEN_RENEWAL_DAYS = 1;
    @Autowired
    private JwtUtils jwtUtils;

    /**
     * 异步有两种方法，
     * 一种是自定义的，自定义ThreadPoolExecutor线程池进行管理代码块
     * 一种是交给Spring管理，通过@Async注解完成，这个注解是对该代码块进行包装
     *      然后将这个代码块丢给线程池处理，使用该方法需要指定线程池，不然会使用默认的
     *      结合 ThreadPoolConfig
     */
//    ThreadPoolExecutor threadPoolExecutor;

    @Override
    @Async
    public void renewalTokenIfNecessary(String token) {
//        threadPoolExecutor.execute(()->{
            Long uid = getValidUid(token);
            String userTokenKey = getUserTokenKey(uid);
            // 获取过期时间
            Long expireDays = RedisUtils.getExpire(userTokenKey,TimeUnit.DAYS);
            if(expireDays == -2){// 不存在的key
                return;
            }
            if(expireDays < TOKEN_RENEWAL_DAYS){ // 重新设置值
                RedisUtils.expire(getUserTokenKey(uid),TOKEN_EXPIRE_DAYS, TimeUnit.DAYS);
            }
//        });
    }

    @Override
    public String login(Long uid) {
        // 使用jwt生成token
        String token = jwtUtils.createToken(uid);
        // 保存token到redis,并且设置过期时间
        RedisUtils.set(getUserTokenKey(uid),token,TOKEN_EXPIRE_DAYS, TimeUnit.DAYS);
        return token;
    }

    @Override
    public Long getValidUid(String token) {
        Long uid = jwtUtils.getUidOrNull(token);
        if(Objects.isNull(uid)){
            return null;
        }
        String oldToken = RedisUtils.get(getUserTokenKey(uid));
        if(StrUtil.isBlank(oldToken)){
            return null;
        }
        return Objects.equals(oldToken,token) ? uid : null;
    }

    private String getUserTokenKey(Long uid){
        return RedisKey.getKey(RedisKey.USER_TOKEN_STRING, uid);
    }


}
